package com.learn.sqlSession;

import com.learn.config.BoundSql;
import com.learn.pojo.Configuration;
import com.learn.pojo.MappedStatement;
import com.learn.utils.GenericTokenParser;
import com.learn.utils.ParameterMapping;
import com.learn.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @author suyafei
 */
public class SimpleExecutor implements Executor  {
    @Override
    public void update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        getPreparedStatement(configuration, mappedStatement, params).execute();
    }

    @Override
    public void delete(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        getPreparedStatement(configuration, mappedStatement, params).execute();
    }

    @Override
    public void insert(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        getPreparedStatement(configuration, mappedStatement, params).execute();

    }

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {

        //执行slq
        ResultSet resultSet = getPreparedStatement(configuration, mappedStatement, params).executeQuery();

        //封装返回结果集
        Class<?> resultClass = getClassType(mappedStatement.getResultType());

        ArrayList<Object> objects = new ArrayList<>();
        while (resultSet.next()) {
            Object resultObject = resultClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                //字段名
                String columnName = metaData.getColumnName(i);
                //字段的值
                Object value = resultSet.getObject(columnName);
                //使用反射，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(resultObject,value);
            }
            objects.add(resultObject);
        }

        return (List<E>) objects;
    }

    /**
     * 通过反射或者参数类或者结果集类
     * @param parameterType
     * @return
     */
    private Class<?> getClassType(String parameterType) {
        if (parameterType != null) {
            Class<?> classType = null;
            try {
                classType = Class.forName(parameterType);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            return classType;
        }else {
            return null;
        }
    }

    /**
     * 完成#{}的解析工作：
     * 1.将#{}使用？进行代替
     * 2.解析出来#{}里面的值进行存储
     * @param sql
     * @return
     */

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析出来的sql
        String parseSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;
    }

    /**
     * 构建PreparedStatement
     * @param configuration
     * @param mappedStatement
     * @param params
     * @return
     * @throws Exception
     */
    private PreparedStatement getPreparedStatement(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception{
        //1.注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        //2.获取sql语句:select * from user where id = #{id} and username = #{username}
        //  转换sql语句:select * from user where id = ? and username = ? ,转换过程中对#{}里面进行解析保存
        String sql = mappedStatement.getSql();

        BoundSql boundSql = getBoundSql(sql);

        //3.获取预处理对象：preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        //4.设置参数
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();

        //获取到了参数的全路径
        String parameterType = mappedStatement.getParameterType();

        for (int i = 0; i < parameterMappings.size(); i++) {
            String content = parameterMappings.get(i).getContent();

            //反射
            Class<?> classType = getClassType(parameterType);

            Field field = classType.getDeclaredField(content);
            //设置暴力访问
            field.setAccessible(true);

            Object o = field.get(params[0]);

            preparedStatement.setObject(i + 1,o);

        }
        return preparedStatement;
    }
}
